package com.blog.interceptor.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.blog.entity.User;
/**
 * 拦截器适配器，相对于HandlerInterceptro接口来说，继承此抽象类可是只实现想要的方法。
 * @author Administrator
 *
 */
public class LoginInterceptor extends HandlerInterceptorAdapter{
	private static Logger log = Logger.getLogger(LoginInterceptor.class);
	
	
	/**
	 * 获取用户的登陆状态。
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// TODO 自动生成的方法存根
		log.info(Thread.currentThread().getStackTrace()[1].getMethodName()+"被调用,返回true则将控制权交由下一个拦截器。。");
		HttpSession session = request.getSession();
		 Object obj = session.getAttribute("username");
		 if(obj  instanceof User){
			 User user = (User) obj; 
			 if(user.getName()!=null){
			 log.info("用户 	"+user.getName()+"  已登录。");
			 return true;
			 }
			 
		 }
		 log.info("SORRY,用户未登陆。");
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO 自动生成的方法存根
		super.afterCompletion(request, response, handler, ex);
		log.info(Thread.currentThread().getStackTrace()[1].getMethodName()+ "方法被调用。");
	}

	@Override
	public void afterConcurrentHandlingStarted(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// TODO 自动生成的方法存根
		super.afterConcurrentHandlingStarted(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO 自动生成的方法存根
		super.postHandle(request, response, handler, modelAndView);
		log.info("此方法作为处理器的后处理被调用，不过是在渲染视图之前。");
	}
	
}
